package com.example.mydemo

import android.graphics.SurfaceTexture
import android.os.Handler
import android.os.HandlerThread
import android.os.Message
import com.example.mydemo.utils.EGLConfigManager

class GLHandlerThread(private val mRenderer: IMyRender?) : HandlerThread("GLHandlerThread"), Handler.Callback {

    companion object {
        const val MSG_INIT = 1
        const val MSG_ON_SIZE_CHANGE = 2
        const val MSG_DATAFRAME = 3
        const val MSG_ON_DESTROY = 4
    }

    var mSurfaceTexture: SurfaceTexture? = null

    override fun handleMessage(msg: Message): Boolean {
        when (msg.what) {
            MSG_INIT -> {
                if (mSurfaceTexture != null) {
                    EGLConfigManager.destroyLEGLESSContext()
                    if (EGLConfigManager.createEglContext(mSurfaceTexture)) {
                        mRenderer?.onSurfaceCreated()
                    }
                }
            }

            MSG_ON_SIZE_CHANGE -> {
                val obj = msg.obj as IntArray
                val width = obj[0]
                val height = obj[1]
                mRenderer?.onSurfaceChanged(width, height)
            }

            MSG_DATAFRAME -> drawFrame()
            MSG_ON_DESTROY -> onDestroy()
        }
        return true
    }

    /**
     * 绘制每一帧
     */
    private fun drawFrame() {
        var isLastFrame = false
        while (!isLastFrame) {
            // 绘制
            isLastFrame = mRenderer?.onDrawFrame() ?: true
            // 一帧完成之后，调用eglSwapBuffers(EGLDisplay dpy, EGLContext ctx)来显示
            EGLConfigManager.swapBuffer()
        }
    }

    /**
     * 退出绘制
     */
    private fun onDestroy() {
        mRenderer?.onDestroy()
        EGLConfigManager.destroyLEGLESSContext()
        mSurfaceTexture = null
        quitSafely()
    }
}